package com.yunmai.library.db;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * RxJava操作数据库实现类
 *
 * @author liyi
 *         create at 2018/3/26
 **/
public class RxJavaAdapter<T> implements DBManagerAdapter {

    /**
     * 将操作请求转换为实际的返回值
     *
     * @param dbCall
     * @return
     */
    public T aapt(final DBCall dbCall) {

        Observable<?> observable = Observable.create(new ObservableOnSubscribe<Result>() {
            @Override
            public void subscribe(ObservableEmitter<Result> e) throws Exception {
                e.onNext(dbCall.request());
            }
        }).flatMap(new Function<Result, Observable<?>>() {
            @Override
            public Observable<T> apply(Result result) throws Exception {
                return (Observable<T>) Observable.just(result.result);
            }
        })
            .subscribeOn(Schedulers.io());
        return (T) observable;
    }

}
